package com.example.mysql.zendesk.framework;

import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.deserialization.EventDeserializer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashSet;
import java.util.Set;

public class BinaryLogClientBean implements ApplicationContextAware, InitializingBean, DisposableBean {
    private final BinaryLogClient client;

    public BinaryLogClientBean(BinaryLogClient client) {
        this.client = client;
        EventDeserializer eventDeserializer = new EventDeserializer();
        //时间反序列化的格式
        eventDeserializer.setCompatibilityMode(
            EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG,
            EventDeserializer.CompatibilityMode.CHAR_AND_BINARY_AS_BYTE_ARRAY
        );
        this.client.setEventDeserializer(eventDeserializer);
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        Set<TableListener> listeners = new HashSet<>(ctx.getBeansOfType(TableListener.class).values());
        BinlogDispatcherListener binlogListener = new BinlogDispatcherListener(listeners);
        this.client.registerEventListener(binlogListener);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.client.connect();
    }

    @Override
    public void destroy() throws Exception {
        this.client.disconnect();
    }
}
